#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdbool.h>

#define MAX_PENDING 16
#define BUFFER_SIZE 32

void handle_client(int socket_handle) {
	char buffer[BUFFER_SIZE];
	int received = -1;
	if ((received = recv(socket_handle, buffer, BUFFER_SIZE, 0)) < 0) {
		fprintf(stderr, "Couldn't receive initial bytes from client.\n");
		exit(1);
	}
	while (received > 0) {
		if (send(socket_handle, buffer, received, 0) != received) {
			fprintf(stderr, "Couldn't send bytes to client.\n");
			exit(1);
		} 
		if ((received = recv(socket_handle, buffer, BUFFER_SIZE, 0)) < 0) {
			fprintf(stderr, "Couldn't receive additional bytes from client.\n");
			exit(1);
		}
	}
	printf("\n");
	close(socket_handle);
}

int main(int argc, char **argv) {
	int server_socket_handle, client_socket_handle;
	struct sockaddr_in echo_server, echo_client;

	if (argc < 2) {
		fprintf(stderr, "Not enough arguments: <port>\n");
		return 1;
	}

	if ((server_socket_handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
		fprintf(stderr, "Couldn't create socket.\n");
		return 1;
	}

	memset(&echo_server, 0, sizeof(echo_server));
	echo_server.sin_family = AF_INET;
	echo_server.sin_addr.s_addr = htonl(INADDR_ANY);
	echo_server.sin_port = htons(atoi(argv[1]));

	if (bind(server_socket_handle, (struct sockaddr *) &echo_server, sizeof(echo_server)) < 0) 	
	{
		fprintf(stderr, "Couldn't bind the server socket.\n");
		return 1;
	}

	if (listen(server_socket_handle, MAX_PENDING) < 0) {
		fprintf(stderr, "Couldn't listen on server socket.\n");
		return 1;
	}

	while (true) {
		unsigned int client_length = sizeof(echo_client);
		if ((client_socket_handle = accept(server_socket_handle, (struct sockaddr *) &echo_client, &client_length)) < 0) {
			fprintf(stderr, "Couldn't accept client connections.\n");
			return 1;
		}
		printf("Client connected: %s: ", inet_ntoa(echo_client.sin_addr));
		handle_client(client_socket_handle);
	}
	return 0;
}
           
